<?php

namespace app\service;


use GuzzleHttp\Client;
use plugin\saiadmin\exception\ApiException;
use support\Log;

class  MediaAnalyzeService
{
    public function analyze($url)
    {
        if (strpos($url, 'douyin') !== false) {
            $analyzeResult = $this->analyzeDyUrl($url);
        } else {
            throw new ApiException('您输入的链接不支持解析');
        }
        return $analyzeResult;
    }

    //抖音
    public function analyzeDyUrl($url)
    {
        $headers = get_headers($url, 1);
        if (isset($headers['Location'])) {
            preg_match('/\d+\s*/', $headers['Location'][0], $videoInfo);
            if ($videoInfo) {
                $videoId = $videoInfo[0];
            } else {
                throw new ApiException('您输入的链接不支持解析');
            }
        } else {
            preg_match('/\d+\s*/', $url, $videoInfo);
            if ($videoInfo) {
                $videoId = $videoInfo[0];
            } else {
                throw new ApiException('您输入的链接不支持解析');
            }
        }
        $client = new Client();
        $videoUrl = 'https://www.douyin.com/aweme/v1/web/aweme/detail/?';
        $payload = [
            'device_platform'=>'webapp',
            'aid'=>'6383',
            'channel'=>'channel_pc_web',
            'aweme_id'=>$videoId,
            'update_version_code'=>'170400',
            'pc_client_type'=>'1',
            'pc_libra_divert'=>'Windows',
            'version_code'=>'190500',
            'version_name'=>'19.5.0',
            'cookie_enabled'=>'true',
            'screen_width'=>'1920',
            'screen_height'=>'1080',
            'browser_language'=>'zh-CN',
            'browser_platform'=>'Win32',
            'browser_name'=>'Chrome',
            'browser_version'=>'128.0.0.0',
            'browser_online'=>'true',
            'engine_name'=>'Blink',
            'engine_version'=>'128.0.0.0',
            'os_name'=>'Windows',
            'os_version'=>'10',
            'cpu_core_num'=>'12',
            'device_memory'=>'8',
            'platform'=>'PC',
            'downlink'=>'10',
            'effective_type'=>'4g',
            'round_trip_time'=>'0',
            'webid'=>'7179497288276362752',
            'msToken'=>'UP0EKwWdvGu7g43mLQd-ayrohjuZsPa2ngVJ798S3l4fMd0IU1Af7hX7wHpJ-1mMyc0oVlZEkQ-lotWH3xz9_SbrJnb3Whj_eIb2tN7S4ixEkSZVu2kFJCNYKQkfBLSjDgC9LjHILBV9v8bf86XQpnPz9EUh_qolkHhpeE7j2hbReC50negOkw=='
        ];
        $urlParams = http_build_query($payload);
        $userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36';
        //$payload['a_bogus'] = $this->getAbs($urlParams, $userAgent);
        $payload['a_bogus'] = 'YfWh/V8fdDDskfWX55nLfY3qVIe3YD000SVkMDhe9dvLJy39HMYk9exEw7zvMIubZsQdIbmjy4hGapPME/OjA36UHmJx/2aBm6Ypt-PZ5oWSs1Xce6UgrUkP-hsdSPB15hNUiKiMoJFCb0G6B3Bz/fH8';
        $headers = [
            'Cookie' => env('DOUYIN_COOKIE'),
            'User-Agent' => $userAgent
        ];
        $videoRequestUrl = $videoUrl . http_build_query($payload);
        $response = $client->get($videoRequestUrl, ['headers' => $headers, 'verify' => false, 'timeout' =>5,'allow_redirects' => false]);
        $videoInfo = json_decode($response->getBody()->getContents(), true);
        $msg = '获取信息失败,请稍后重试';
        if (!$videoInfo) {
            Log::info('视频详情', [$videoInfo]);
            throw new ApiException($msg);
        }
        if ($videoInfo['status_code'] != 0 || !$videoInfo['aweme_detail']) {
            if (isset($videoInfo['filter_detail']['detail_msg'])) {
                $msg = $videoInfo['filter_detail']['detail_msg'];
            }
            throw new ApiException($msg);
        }
        //图集
        if ($videoInfo['aweme_detail']['media_type'] == 2) {
            $urlList = array_column($videoInfo['aweme_detail']['images'], 'url_list');
            $mediaInfo = array_map(function ($item) {
                return $item[0];
            }, $urlList);
        } else if ($videoInfo['aweme_detail']['media_type'] == 4) {
           // $mediaInfo = $videoInfo['aweme_detail']['video']['play_addr']['url_list'][0] ?? '';
            $mediaInfo = $videoInfo['aweme_detail']['video']['play_addr']['url_list'];
        } else {
            $mediaInfo = [];
        }
        return $mediaInfo;
    }

    public function getAbs($query, $userAgent)
    {
        //$cmd = sprintf("node %s/resources/A-Bogus-New.js '%s' %s '%s'", app_path(),$query, json_encode([]), $userAgent);
        $cmd = sprintf("node %s/resources/A-Bogus-New.js '%s' '%s' '%s'", app_path(), $query, '[]', $userAgent);
        Log::info($cmd);
        // 执行命令并获取输出
        $output = shell_exec($cmd);
        Log::info($output);
        return $output;
    }
}
